﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CLFramework.Windows.Forms;
using System.Xml;
using StockMonitor.Helper;
using CLFramework.Utility;
using StockMonitor.Configuration;
using System.Threading;
using CLFramework.Utility;

namespace StockMonitor.UserControls
{
    [ModuleContract("652DBA8B-721A-4CEB-B50D-5028CC730755", "查询(&Q)", "成交查询")]
    public partial class UCBusinessQuery : MdiUserControl
    {
        #region Ctor.

        public UCBusinessQuery()
            : base()
        {
            InitializeComponent();

            this.cbStockCode.DataSource = StockListConfig.Instance.AllStock;
            this.cbStockCode.DisplayMember = "StockName";
            this.cbStockCode.ValueMember = "StockCode";
        }

        public UCBusinessQuery(XmlNode node)
            : this()
        {
            InitializeComponent();
        }

        #endregion

        #region MidUserControl Members

        public override void Onload()
        {
            this.dgvBusinessQ.AutoGenerateColumns = false;
            this.dgvBusinessHistory.AutoGenerateColumns = false;
            ThreadPool.QueueUserWorkItem(o =>
            {
                RefreshTodayBusiness();
            });
        }

        public override void Unload()
        {
        }

        #endregion

        #region Event Handlers

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RefreshTodayBusiness();
        }

        private void btnBusinessQ_Click(object sender, EventArgs e)
        {
            QueryHistoryBusiness(this.dtpBeginDate.Value, this.dtpEndDate.Value.AddDays(-1), this.cbStockCode.SelectedValue.ToString());
        }

        private void cbAutoRefresh_CheckedChanged(object sender, EventArgs e)
        {
            if (cbAutoRefresh.Checked)
            {
                timeAutoBQ.Enabled = true;
                timeAutoBQ.Interval = AppSettings.GetValue<int>("AutoRefreshInterval");
            }
            else
                timeAutoBQ.Enabled = false;
        }

        private void timeAutoBQ_Tick(object sender, EventArgs e)
        {
            RefreshTodayBusiness();
        }

        #endregion

        #region Methods

        /// <summary>
        /// 刷新今日成交记录.
        /// </summary>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 5:47 PM</datetime>
        /// </remarks>
        private void RefreshTodayBusiness()
        {
            try
            {
                TradeContext.Instance.UpdateTodayBusiness();
            }
            catch (HsGateway.HsCommException hsex)
            {
                Log.Exception("交易接口返回错误", hsex);
            }
            catch (Exception ex)
            {
                Log.Exception("捕获到系统错误D01", ex);
            }

            if (this.lbLastUpdatedTimeBQ.InvokeRequired)
            {
                this.Invoke(new Action(UpdateTodayBusinessUI));
            }
            else
            {
                UpdateTodayBusinessUI();
            }
        }

        private void UpdateTodayBusinessUI()
        {
            this.lbLastUpdatedTimeBQ.Text = DateTime.Now.ToString("hh:mm:ss");
            this.dgvBusinessQ.DataSource = new SortableBindingList<BusinessRecord>(TradeContext.Instance.TodayBusiness);
            this.dgvBusinessQ.Update();
            this.dgvBusinessQ.Refresh();
        }

        private void QueryHistoryBusiness(DateTime dtStart, DateTime dtEnd, string stockCode)
        {
            try
            {
                if (stockCode != string.Empty)
                    this.dgvBusinessHistory.DataSource = new SortableBindingList<BusinessRecord>(TradeContext.Instance.UpdateHistoryBusiness(dtStart, dtEnd).Where(b => b.StockCode == stockCode).ToList());
                else
                    this.dgvBusinessHistory.DataSource = new SortableBindingList<BusinessRecord>(TradeContext.Instance.UpdateHistoryBusiness(dtStart, dtEnd));

                this.dgvBusinessHistory.Update();
                this.dgvBusinessHistory.Refresh();
            }
            catch (HsGateway.HsCommException hsex)
            {
                Log.Exception("交易接口返回错误", hsex);
            }
            catch (Exception ex)
            {
                Log.Exception("捕获到系统错误D02", ex);
            }
        }

        #endregion

        private void btnExport_Click(object sender, EventArgs e)
        {
            ExcelHelper.ExportToExcel(this.dgvBusinessHistory);
        }

    }
}
